<template>
  <view class="wrap">
    <TabBar theme="white" :currentIndex="4" />
    <view class="mycenter-header">
      <view class="mycenter-header-top">
           <u-icon name="list" color="#fff" size="32" @click="$u.route('/pagesB/setting/setting',{userInfo})"></u-icon>
      </view>
      <view class="mycenter-header-content">
        <u-avatar
          class="mycenter-header-content-avatar"
          size="large"
          :src="userInfo.headimgurl"
        />
        <view class="mycenter-header-content-name">
          <block v-if="userInfo.user_name ">
          <h3>{{ userInfo.user_name }}</h3>
          <p class="mycenter-header-content-id">视频号：1133434</p>
          </block>
          		<!--  #ifndef  MP-WEIXIN -->
						<view class="login f34 c3 colorWhite" v-else>
							@click="navigateTo('/pagesB/login/login')">{{$t('登录')}}/{{$t('注册')}}</view>
						<!--  #endif -->
						<!--  #ifdef  MP-WEIXIN -->
						<u-button size="mini" style="margin:0 30upx " shape="circle" type="success" v-if="!isLogin"
							lang="zh_CN" @click="wechatLogin">{{$t('微信登录')}}
						</u-button>
						<!--  #endif -->
        </view>
      </view>
      <view class="bg-blur"></view>
    </view>

    <view class="mycenter-content">
      <view class="mycenter-content-statistics">
        <p class="mycenter-content-statistics-p">
          <span class="mycenter-content-statistics-number">7</span>
          <span>获赞</span>
        </p>
        <p class="mycenter-content-statistics-p">
          <span class="mycenter-content-statistics-number">{{
            userInfo.short_video_count
          }}</span>
          <span>作品</span>
        </p>
        <p class="mycenter-content-statistics-p">
          <span class="mycenter-content-statistics-number">{{
            userInfo.coll_num
          }}</span>
          <span>关注</span>
        </p>
        <p class="mycenter-content-statistics-p">
          <span class="mycenter-content-statistics-number">{{
            userInfo.follow_me
          }}</span>
          <span>粉丝</span>
        </p>
      </view>
      <view>
        <view class="mycenter-introduce">
          点击添加介绍，让大家认识你
          <u-icon name="edit-pen" color="#666" size="28"></u-icon>
        </view>
        <view class="mycenter-profile">
          <view class="mycenter-profile-item" v-if="userInfo">
            <u-icon
              :name="userInfo.sex !== 1 ? 'woman' : 'man'"
              :color="userInfo.sex !== 1 ? '#ff6262' : '#3eb2ff'"
              size="28"
            ></u-icon>
            <span v-if="getUserBirth">{{ getUserBirth }}岁</span>
          </view>
        </view>
      </view>
      <view class="u-m-t-20 mycenter-content-wrap">
        <view class="mycenter-content-item" @click="goMyShopperCenter">
          <view class="mycenter-content-item-iconwrap">
            <!-- <shopping theme="outline" size="19" fill="#333" /> -->
          </view>
          <p class="mycenter-content-item-title">
            <span class="mycenter-content-item-title-sub">我的商城</span>
            <span>美好生活触手可得</span>
          </p>
        </view>
        <!-- <view class="mycenter-content-item">
          <view class="mycenter-content-item-iconwrap">
            <History theme="outline" size="19" fill="#333" />
          </view>
          <p class="mycenter-content-item-title">
            <span class="mycenter-content-item-title-sub">浏览记录</span>
            <span>美好生活触手可得</span>
          </p>
        </view> -->
      </view>

      <view>
        <view class="mycenter-video">
          <u-sticky h5-nav-height="0" @fixed="stickyFixed" @unfixed="stickyunFixed">
            <view>
              <u-navbar :is-back="false" :title="userInfo.user_name" v-show="isSticky">
                <view slot="right" class="mycenter-video-navbar-right" >
                  <u-icon name="list" color="#333" size="32"  @click="$u.route('/pagesB/setting/setting',{userInfo})"></u-icon>
                </view>
              </u-navbar>
              <!-- 只能有一个根元素 -->
              <u-tabs-swiper
                ref="uTabs"
                :list="tabList"
                active-color="#333"
                inactive-color="#666"
                font-size="28"
                :current="current"
                @change="tabsChange"
                :is-scroll="false"
                swiperWidth="750"
              ></u-tabs-swiper>
            </view>
          </u-sticky>

          <swiper
            class="mycenter-swiper"
            :current="swiperCurrent"
            @transition="transition"
            @animationfinish="animationfinish"
          >
            <swiper-item
              class="swiper-item"
              v-for="(item, index) in tabList"
              :key="index"
            >
             <block v-if="getCurrentVideoList && getCurrentVideoList.length">
                    <view
                class="mycenter-video-wrap"
                v-for="(video,  vi) in getCurrentVideoList"
                @click="goPlayVideo(video)"
              >
                <u-image
                  :src="video.cover_img"
                  width="100%"
                  height="290"
                ></u-image>
                <view class="mycenter-video-wrap-heart">
                     <u-icon class="mycenter-video-wrap-heartIcon" name="heart" color="#fff" size="28"></u-icon>
                     {{ video.praise_num>10000? `${(video.praise_num/10000).toFixed(1)}万`:  video.praise_num }}
                </view>
               
              </view>
             </block>
            <view class="video-empty" v-else>
                <h5 class="video-empty-title">{{ item.emptyTip.title }}</h5>
                <p>{{ item.emptyTip.desc }}</p>
            </view>
            </swiper-item>

          </swiper>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import TabBar from "@/components/tabBar/index";
const relativeTime = require("dayjs/plugin/relativeTime");
import dayjs from "dayjs";
dayjs.extend(relativeTime);

export default {
  data() {
    return {
      userInfo: {},
        page: 1,
        isSticky:false,
      videoTabType: "myVideo", // 三种类型： myVideo：我的作品    favorite:收藏    like：喜欢
      videoData: {
        myVideo: {},
        favorite: {},
        like: {},
      },
      // 因为内部的滑动机制限制，请将tabs组件和swiper组件的current用不同变量赋值
      current: 0, // tabs组件的current值，表示当前活动的tab选项
      swiperCurrent: 0, // swiper组件的current值，表示当前那个swiper-item是活动的
    };
  },
  components: {
    TabBar
  },
  onLoad() {
    this.getUserInfo();
    this.tabList = [
      {
        name: "作品",
        type: "myVideo",
            emptyTip: {
                title: '暂无作品',
                desc: '发布你的第一条视频'
        }
      },
      {
        name: "收藏",
        type: "favorite",
          emptyTip: {
                title: '暂无收藏',
                desc: '前往短视频推荐刷刷视频吧~'
        }
      },
      {
        name: "喜欢",
          type: "like",
          emptyTip: {
                title: '暂无喜欢的作品',
                desc:  '前往短视频推荐刷刷视频吧~'
        }
      },
    ];

    	// 初始化时获取小程序秘钥code 换取openId  （仅在初始化时获取一次，不要放在事件中重复获取会解密失败）
			// #ifdef MP-WEIXIN
			uni.login({
				provider: "weixin",
				success: loginRes => {
					this.wecode = loginRes.code
				},
				fail: (err) => {
					this.$toast(JSON.stringify(err));
				},
			});
			// #endif
  },
  computed: {
    getUserBirth() {
      const birth = dayjs(this.userInfo.birth).fromNow(true) || "";
      return birth.split(" ")[0];
    },
    getCurrentVideoList() {
      return this.videoData[this.videoTabType]["list"];
    },
  },
  methods: {
    getUserInfo() {
      this.$http.getUserInfo().then((res) => {
        if (res.status == 200) {
          uni.setStorageSync("userInfo", JSON.stringify(res.data));
          this.userInfo = res.data;
          console.log(res.data);
          this.isLogin = 1;
          this.getShopVideoList();
          // vuex 提交用户信息
          this.$store.commit("setUserInfo", res.data);
        }
      });
    },
    getShopVideoList() {
      const { id } = this.userInfo;
      this.$http
        .getShopVideoList({ view_user_id: id, page: this.page })
        .then((res) => {
          const { status, data } = res;
          if (status === 200) {
            this.videoData[this.videoTabType] = {
              list: data,
              page: this.page,
            };
          }
        });
      },
      goPlayVideo(video) {
        const {id} = video
          this.$u.route({
              url: process.env.VUE_APP_PLATFORM !== 'app-plus' ? '/pagesB/shortVideo/h5mpShortVideo' : '/pagesB/shortVideo/appShortVideo',
              params: {
                id
              }
        })
      },
      stickyFixed() {
        this.isSticky=true
      },
      stickyunFixed() {
         this.isSticky=false
     },
  	// #ifdef MP-WEIXIN
			// 微信小程序登录   code换区 小程序openid 和 session_key
			getOpenID() {
				return new Promise((resolve) => {
					this.$http.getWechatMiniProgramOpenid({
						code: this.wecode
					}).then(res => {
						resolve(res.data)
						
					});
				})
			},
			async wechatLogin() {
				this.inviterID = this.inviterInfo && this.inviterInfo.id
        const { openid = '', session_key = '', unionid = '' } = await this.getOpenID()
        debugger
				uni.setStorageSync('xcxOpenid', openid); //存取小程序openid
				session_key && uni.setStorageSync('xcxSessionKey', session_key);
				this.asyncUserInfo(openid, unionid);	
				this.isInviteModelShow = false;
				
			},
			asyncUserInfo(openid = '', unionid = '') {
				if (openid == '') {
					return false;
				}
				this.$http.thirdLogin({
					oauth: 'weixin_mp',
					openid: openid,
					unionid: unionid,
					nick_name: this.nickName,
					uniongender: this.gender,
					iconurl: this.avatarUrl,
					inviter: this.inviterID
				}).then(result => {
					this.$toast(result.status)
					if (result.status == 200) {
						this.$store.commit('loginStatus', true)
						uni.setStorageSync('token', result.data.token);
						uni.setStorageSync('identity', result.data.identity);
						uni.setStorageSync('role', result.data.role);
						uni.setStorageSync('role_id', result.data.shop_id);
						uni.closeSocket({
							success() {
								console.log('socket关闭成功');
							},
							fail(res) {
								console.log(res);
							}
						})
						setTimeout(() => {
							this.im();
							this.$u.route({
								url: "/pagesB/tabBar/cart",
								type: "reLaunch"
							})
						}, 500);

					}
					if (result.status == 400 || result.data.info == 'unregister') {
						console.log(result)
						this.$u.route({
							url: 'platforms/mp-weixin/miniLogin',
							params: {
								oauth: 'weixin_mp',
								openid: openid,
								unionid: unionid,
								nick_name: this.nickName,
								uniongender: this.gender,
								iconurl: this.avatarUrl,
								inviter: this.inviterID,
							}
						});
					}
				})
			},
			// #endif
    goMyShopperCenter() {
      this.$u.route({
        url: "/pagesB/tabBar/cart",
      });
    },
    tabsChange(index) {
      this.swiperCurrent = index;
      this.videoTabType = (this.tabList[index] || {}).type;
    },
    transition(e) {
      let dx = e.detail.dx;
      this.$refs.uTabs.setDx(dx);
    },
    // 由于swiper的内部机制问题，快速切换swiper不会触发dx的连续变化，需要在结束时重置状态
    // swiper滑动结束，分别设置tabs和swiper的状态
    animationfinish(e) {
      let current = e.detail.current;
      this.$refs.uTabs.setFinishCurrent(current);
      this.swiperCurrent = current;
      this.current = current;
    },
    onreachBottom() {
      this.videoData[this.videoTabType].page += 1;
    },
  },
};
</script>

<style lang="scss" scoped>
.commonpadding{
    padding: 0 30rpx;
}
.mycenter {
  &-header {
    position: relative;
    background-image: url(../../static/images/wallet-bg.jpg);
    background-size: cover;
    background-position: center center;
    &-top{
        position:absolute;
        top:30rpx;
        right:20rpx;
        z-index:999
    }
    &-content {
      position: relative;
      z-index: 10;
      display: flex;
      align-items: center;
      color: #fff;
      padding: 190rpx 30rpx 50rpx 30rpx;
      &-name {
        margin-left: 20rpx;
      }
      &-id {
        color: #999;
      }
      &-avatar {
        border: 3px solid #fff;
        border-radius: 400rpx;
      }
    }
  }
  &-content {
    border-top-right-radius: 16rpx;
    border-top-left-radius: 16rpx;
    margin-top: -30rpx;
    position: relative;
    z-index: 10;
    overflow: hidden;
    background: #fff;
    padding: 20rpx 0;
    width: 100%;
    &-wrap {
      margin: 30rpx 0;
      @extend .commonpadding;
      display:flex;
      flex-wrap:nowrap
    }
    &-statistics {
      display: flex;
      margin: 20rpx 0;
      @extend .commonpadding;
      &-p {
        display: flex;
        align-items: center;
        margin-right: 20rpx;
        color: #555;
        font-size: 12px;
      }
      &-number {
        font-size: 16px;
        font-weight: bold;
        margin-right: 6rpx;
        color: #333;
      }
    }
    &-item {
      display: flex;
      flex-shrink: 0;
      align-items: center;
      width: 270rpx;
      margin-right: 30rpx;
      &-iconwrap {
        background-color: #eee;
        width: 60rpx;
        height: 60rpx;
        display: flex;
        margin-right: 20rpx;
        justify-content: center;
        align-items: center;
        border-radius: 10rpx;
      }
      &-title {
        display: flex;
        font-size: 12px;
        color: #999;
        flex-direction: column;
        &-sub {
          font-size: 14px;
          font-weight: 500;
          color: #333;
        }
      }
    }
  }
  &-introduce {
    font-size: 12px;
    margin: 10rpx 0;
     @extend .commonpadding;
  }
  &-profile {
    margin: 20rpx 0;
     @extend .commonpadding;
    &-item {
      display: inline-flex;
      align-items: center;
      background-color: #eee;
      padding: 4rpx 10rpx;
      border-radius: 6rpx;
      font-size: 12px;
    }
    color: #555;
  }
  &-video {
    height: 80vh;
    &-navbar-right{
        margin-right: 30rpx;
    }
    &-wrap {
      display: flex;
      width: calc(100% / 3);
      border:1px solid #fff;
      position:relative;
      &-heart{
        position: absolute;
        bottom: 10rpx;
        left: 10rpx;
        color:#Fff;
        font-size:12px;
        &Icon{
            margin-right:8rpx
        }
      }
      &:nth-child(3n+1){    
        border-left-width: 0;
      }
        &:nth-child(3n){    
        border-right-width: 0;
      }
    }
  }
  &-swiper {
    height: inherit;
  }
}

.uni-scroll-view-content {
  display: flex;
}
.bg-mycenter {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 0;
}
.bg-blur {
  background-image: linear-gradient(to top, #1d1d1d, transparent);
  height: 360rpx;
  width: 100%;
  position: absolute;
  bottom: 0;
}
.video-empty{
    text-align:center;
    padding:100rpx;
    width:100%;
    color:#666;
    font-size:28rpx;
    &-title{
        font-size: 32rpx;
        margin-bottom:16rpx;
        color:#333
    }
}
/deep/ uni-swiper-item {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}
</style>